package com.glx.test.datafluxaispringboot.controller;

import com.glx.test.datafluxaispringboot.service.DeepSeekService;
import com.glx.test.datafluxaispringboot.service.StreamChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
@RequestMapping("/api/v1")
@CrossOrigin(origins = "*")
@Slf4j
public class OpenAIController {
    private final ExecutorService executor = Executors.newCachedThreadPool();
    private final StreamChatService streamChatService;
    private final DeepSeekService deepSeekService;

    @Autowired
    public OpenAIController(StreamChatService streamChatService, DeepSeekService deepSeekService) {
        this.streamChatService = streamChatService;
        this.deepSeekService = deepSeekService;
    }

    @GetMapping(value = "/stream-chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter streamChat(
            @RequestParam String question,
            @RequestParam(required = false) String sessionId
    ) {
        SseEmitter emitter = new SseEmitter(60_000L); // 60秒超时

        executor.execute(() -> {
            try {
                streamChatService.handleStreamChat(question, sessionId, emitter);
                emitter.complete();
            } catch (Exception e) {
                emitter.completeWithError(e);
            }
        });

        return emitter;
    }

    @GetMapping("/translate")
    public String translate(@RequestParam("text") String text,
                            @RequestParam(value = "model",required = false) String model) throws IOException {
        String s = deepSeekService.translateAndSummary(text, "翻译", model);
        log.info("翻译结果：{}", s);
        return s;
    }

    @GetMapping("/summary")
    public String summary(@RequestParam("text") String text,
                          @RequestParam(value = "model",required = false) String model) throws IOException {
        String s = deepSeekService.translateAndSummary(text, "总结", model);
        log.info("总结结果：{}", s);
        return s;
    }
}